{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[ 0.        , -0.33333333],\n",
       "       [-0.25      , -0.16666667],\n",
       "       [ 0.25      ,  0.16666667],\n",
       "       [ 0.5       ,  0.66666667],\n",
       "       [-0.5       , -0.33333333]])"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "\n",
    "A=np.array([\n",
    "    [3,2000],\n",
    "    [2,3000],\n",
    "    [4,5000],\n",
    "    [5,8000],\n",
    "    [1,2000]\n",
    "    \n",
    "],dtype='float')\n",
    "\n",
    "mean=np.mean(A,axis=0)  #按列求平均\n",
    "norm=A-mean   #广播\n",
    "\n",
    "scope=np.max(norm,axis=0)-np.min(norm,axis=0)\n",
    "\n",
    "norm=norm/scope  #缩放\n",
    "norm"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([[-0.2452941 ],\n",
       "       [-0.29192442],\n",
       "       [ 0.29192442],\n",
       "       [ 0.82914294],\n",
       "       [-0.58384884]])"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from sklearn.decomposition import PCA\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.preprocessing import MinMaxScaler\n",
    "\n",
    "def std_PCA(**kwargs):\n",
    "    scaler=MinMaxScaler()  #数据归一化和缩放 \n",
    "    pca=PCA(**kwargs)\n",
    "    pipeline=Pipeline([('scaler',scaler),('pca',pca)])\n",
    "    return pipeline\n",
    "\n",
    "pca=std_PCA(n_components=1)\n",
    "\n",
    "R2=pca.fit_transform(A)\n",
    "\n",
    "R2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pca.inverse_transform(R2)   #还原数据，逆运算"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
